﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MassTransit;
using MassTransit.Contracts.JobService;
using MassTransitDemo.JobService.Consumers;
using Microsoft.AspNetCore.Mvc;

namespace MassTransitDemo.JobService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ConvertVideoController : ControllerBase
    {
        private readonly IRequestClient<ConvertVideo> _client;

        public ConvertVideoController(IRequestClient<ConvertVideo> client)
        {
            _client = client;
        }

        [HttpPost("{path}")]
        public async Task<IActionResult> Get(string path)
        {
            var groupId = NewId.Next().ToString();

            var response = await _client.GetResponse<JobSubmissionAccepted>(new
            {
                path,
                groupId,
                Index = 0,
                Count = 1
            });

            return Ok(new
            {
                response.Message.JobId,
                Path = path
            });
        }

        [HttpGet("{count}")]
        public async Task<IActionResult> Get(int count)
        {
            var jobIds = new List<Guid>(count);

            var groupId = NewId.Next().ToString();

            for (var i = 0; i < count; i++)
            {
                var path = NewId.Next() + ".txt";

                var response = await _client.GetResponse<JobSubmissionAccepted>(new
                {
                    path,
                    groupId,
                    Index = i,
                    count
                });

                jobIds.Add(response.Message.JobId);
            }

            return Ok(new { jobIds });
        }
    }
}
